package ch4;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(name = "LastAccessServlet",value = "/lastAccess")
public class LastAccessServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Date date = new Date ();
        SimpleDateFormat timesdf= new SimpleDateFormat ("yy年MM月dd日  yy:MM:dd");
        String str_time = timesdf.format (date);
        String str_date= URLEncoder.encode (str_time,"utf-8");
        response.setContentType ("text/html;charset=utf-8");
        Cookie[] cookies = request.getCookies ();
        if (cookies != null && cookies.length >0){
            boolean flag=false;
            for (Cookie cookie : cookies){
                String name = cookie.getName ();
                if ("lastAccess".equals (name)){
                    flag = true;
                    String value = cookie.getValue ();
                    System.out.println ("解码前："+value);
                    value = URLDecoder.decode (value,"utf-8");
                    System.out.println ("解码后："+value);
                    response.getWriter ().write ("欢迎回来，您上次访问的时间是："+value);
                    cookie.setValue (str_time);
                    cookie.setMaxAge (60*60*24*30);
                    response.addCookie (cookie);
                    break;
                }
            }
        }else {
            System.out.println ("编码后："+str_date);
            Cookie cookie=new Cookie("lastAccess",str_date);
            cookie.setMaxAge (60*60*24*30);
            response.addCookie (cookie);
            response.getWriter ().write ("你好，欢迎您首次访问");

        }

    }
}




